import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { useVocabulary } from '@/contexts/VocabularyContext';
import StatsDialog from '@/components/stats/StatsDialog';
import AddWordDialog from '@/components/vocabulary/AddWordDialog';
import { ArrowLeft, Plus, Trash2, Search, BarChart3 } from 'lucide-react';
import type { Category, Word } from '@/types/vocabulary';
import { toast } from 'sonner';

const categories: Category[] = ['全部类别', '日常生活', '商务职场', '学术教育', '旅游出行', '科技数码'];

const VocabularyList: React.FC = () => {
  const navigate = useNavigate();
  const { vocabulary, addWord, addWords, deleteWord, gameStats, categoryStats } = useVocabulary();

  const [filterCategory, setFilterCategory] = useState<Category>('全部类别');
  const [searchTerm, setSearchTerm] = useState('');
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [isStatsDialogOpen, setIsStatsDialogOpen] = useState(false);
  const [deleteId, setDeleteId] = useState<string | null>(null);

  const filteredVocabulary = vocabulary.filter((word) => {
    const matchesCategory = filterCategory === '全部类别' || word.category === filterCategory;
    const matchesSearch =
      word.english.toLowerCase().includes(searchTerm.toLowerCase()) ||
      word.chinese.includes(searchTerm);
    return matchesCategory && matchesSearch;
  });

  const handleAddWords = (words: Omit<Word, 'id'>[]) => {
    const wordsWithoutIsCustom = words.map(({ isCustom, ...word }) => word);
    
    if (wordsWithoutIsCustom.length > 1) {
      addWords(wordsWithoutIsCustom);
      toast.success(`成功添加 ${wordsWithoutIsCustom.length} 个单词到词汇表`);
    } else if (wordsWithoutIsCustom.length === 1) {
      addWord(wordsWithoutIsCustom[0]);
      toast.success('单词添加成功');
    }
  };

  const handleDeleteWord = () => {
    if (deleteId) {
      deleteWord(deleteId);
      setDeleteId(null);
      toast.success('单词删除成功！');
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 p-4">
      <div className="container mx-auto max-w-6xl">
        <div className="mb-6">
          <Button variant="ghost" onClick={() => navigate('/')}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回首页
          </Button>
        </div>

        <Card>
          <CardHeader>
            <CardTitle className="text-3xl">词汇表</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex flex-col md:flex-row gap-4 mb-6">
              <div className="flex-1">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                  <Input
                    placeholder="搜索单词..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>
              </div>

              <Select value={filterCategory} onValueChange={(value: Category) => setFilterCategory(value)}>
                <SelectTrigger className="w-full md:w-48">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {categories.map((cat) => (
                    <SelectItem key={cat} value={cat}>
                      {cat}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <Button onClick={() => setIsAddDialogOpen(true)}>
                <Plus className="w-4 h-4 mr-2" />
                添加单词
              </Button>

              <Button variant="outline" onClick={() => setIsStatsDialogOpen(true)}>
                <BarChart3 className="w-4 h-4 mr-2" />
                掌握情况
              </Button>
            </div>

            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-1/3">英文单词</TableHead>
                    <TableHead className="w-1/3">中文释义</TableHead>
                    <TableHead className="w-1/4">类别</TableHead>
                    <TableHead className="w-20 text-center">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredVocabulary.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={4} className="text-center py-8 text-gray-500">
                        没有找到匹配的单词
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredVocabulary.map((word) => (
                      <TableRow key={word.id}>
                        <TableCell className="font-semibold">{word.english}</TableCell>
                        <TableCell>{word.chinese}</TableCell>
                        <TableCell>
                          <span className="inline-block px-2 py-1 bg-blue-100 text-blue-800 rounded text-sm">
                            {word.category}
                          </span>
                        </TableCell>
                        <TableCell className="text-center">
                          {word.isCustom && (
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => setDeleteId(word.id)}
                            >
                              <Trash2 className="w-4 h-4 text-red-600" />
                            </Button>
                          )}
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>

            <div className="mt-4 text-sm text-gray-600">
              共 {filteredVocabulary.length} 个单词
            </div>
          </CardContent>
        </Card>

        <AlertDialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>确认删除</AlertDialogTitle>
              <AlertDialogDescription>
                确定要删除这个单词吗？此操作无法撤销。
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>取消</AlertDialogCancel>
              <AlertDialogAction onClick={handleDeleteWord}>删除</AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>

        <StatsDialog
          open={isStatsDialogOpen}
          onOpenChange={setIsStatsDialogOpen}
          gameStats={gameStats}
          categoryStats={categoryStats}
        />

        <AddWordDialog
          open={isAddDialogOpen}
          onOpenChange={setIsAddDialogOpen}
          onAddWords={handleAddWords}
        />
      </div>
    </div>
  );
};

export default VocabularyList;
